<template>
  <div class="user-manage">
    <el-card>
      <div class="search-bar">
        <div class="search-left">
          <el-input v-model="search" placeholder="搜索用户名" style="width: 200px;" @keyup.enter="fetchUsers" clearable />
          <el-button type="primary" style="margin-left: 8px;" @click="fetchUsers">查询</el-button>
        </div>
        <el-button type="primary" @click="openAddDialog">新增用户</el-button>
      </div>
      <el-table :data="userList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="mobile" label="手机号" />
        <el-table-column
          label="角色"
          :formatter="row => row.roleNames || ''"
        />
        <el-table-column prop="createdTime" label="创建时间" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 16px; text-align: right;"
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="page"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 新增/编辑用户弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType==='add'">
          <el-input v-model="form.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIdList">
          <el-select v-model="form.roleIdList" multiple placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="role in roleOptions"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserList, addUser, updateUser, deleteUser } from '@/api/user'
import { getRoleList } from '@/api/role'

export default {
  name: 'UserManage',
  data() {
    return {
      userList: [],
      total: 0,
      page: 1,
      pageSize: 10,
      search: '',
      dialogVisible: false,
      dialogType: 'add', // add/edit
      dialogTitle: '新增用户',
      roleOptions: [],
      form: {
        id: null,
        username: '',
        password: '',
        mobile: '',
        roleIdList: []
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }]
      }
    }
  },
  methods: {
    async fetchUsers() {
      const params = {
        page: this.page,
        pageSize: this.pageSize,
        search: this.search
      }
      const res = await getUserList(params)
      console.log(res);
      this.userList = res.data.records
      this.total = res.data.total
    },
    handlePageChange(val) {
      this.page = val
      this.fetchUsers()
    },
    async openAddDialog() {
      this.dialogType = 'add'
      this.dialogTitle = '新增用户'
      this.form = { id: null, username: '', password: '', mobile: '', roleIdList: [] }
      await this.fetchRoles()
      this.dialogVisible = true
    },
    async openEditDialog(row) {
      this.dialogType = 'edit'
      this.dialogTitle = '编辑用户'
      this.form = { ...row, password: '', roleIdList: row.roleIdList || [] }
      await this.fetchRoles()
      this.dialogVisible = true
    },
    async fetchRoles() {
      const res = await getRoleList({ page: 1, pageSize: 1000 })
      this.roleOptions = res.data.records
    },
    async handleSubmit() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        if (this.dialogType === 'add') {
          await addUser(this.form)
        } else {
          await updateUser(this.form)
        }
        this.dialogVisible = false
        this.fetchUsers()
      })
    },
    async handleDelete(row) {
      this.$confirm('确定要删除该用户吗？', '提示', { type: 'warning' })
        .then(async () => {
          await deleteUser(row.id)
          this.fetchUsers()
        })
        .catch(() => {})
    },
    roleFormatter(row) {
      if (Array.isArray(row.roleIdList)) {
        return row.roleIdList.map(id => {
          const role = this.roleOptions.find(r => r.id === id)
          return role ? role.name : id
        }).join(', ')
      }
      return row.role || ''
    }
  },
  mounted() {
    this.fetchUsers()
  }
}
</script>

<style scoped>
.user-manage {
  padding: 24px;
}
.search-bar {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-left {
  display: flex;
  align-items: center;
}
</style> 